const { sequelize, testConnection } = require('../../config/database');

// 导入所有模型
const { User, syncUser } = require('./User');
const { RechargeRecord, syncRechargeRecord } = require('./RechargeRecord');
const { Payment, syncPayment } = require('./Payment');
const SystemConfig = require('./SystemConfig');
const { MaterialOrder, syncMaterialOrder } = require('./MaterialOrder');
const { Material, syncMaterial } = require('./Material');
const Cart = require('./Cart');
const Category = require('./Category');
const Tag = require('./Tag');
const Download = require('./Download');
const ConsumptionRecord = require('./ConsumptionRecord');
const MaterialTag = require('./MaterialTag');
const Transaction = require('./Transaction');
const VerificationCode = require('./VerificationCode');

// 导入并应用模型关联关系
require('../../models/associations');

// 初始化所有模型
const initializeModels = async (force = false) => {
  try {
    console.log('开始测试数据库连接...');
    const isConnected = await testConnection();
    if (!isConnected) {
      throw new Error('数据库连接失败');
    }
    console.log('数据库连接测试成功');

    // 同步所有模型
    // 注意：在生产环境中应该谨慎使用 force: true，因为它会删除现有的表
    console.log('开始同步数据库模型...');
    
    // 如果是强制模式，先按照依赖关系反序删除所有表
    if (force) {
      console.log('正在删除现有表...');
      try {
        // 先删除所有外键约束
        await sequelize.query('SET FOREIGN_KEY_CHECKS = 0');
        
        // 删除所有表
        await Promise.all([
          Payment.drop().catch(err => console.log('删除 Payment 表时出错:', err.message)),
          MaterialOrder.drop().catch(err => console.log('删除 MaterialOrder 表时出错:', err.message)),
          Material.drop().catch(err => console.log('删除 Material 表时出错:', err.message)),
          RechargeRecord.drop().catch(err => console.log('删除 RechargeRecord 表时出错:', err.message)),
          SystemConfig.drop().catch(err => console.log('删除 SystemConfig 表时出错:', err.message)),
          User.drop().catch(err => console.log('删除 User 表时出错:', err.message)),
          Cart.drop().catch(err => console.log('删除 Cart 表时出错:', err.message)),
          Category.drop().catch(err => console.log('删除 Category 表时出错:', err.message)),
          Tag.drop().catch(err => console.log('删除 Tag 表时出错:', err.message)),
          Download.drop().catch(err => console.log('删除 Download 表时出错:', err.message)),
          ConsumptionRecord.drop().catch(err => console.log('删除 ConsumptionRecord 表时出错:', err.message)),
          MaterialTag.drop().catch(err => console.log('删除 MaterialTag 表时出错:', err.message)),
          Transaction.drop().catch(err => console.log('删除 Transaction 表时出错:', err.message)),
          VerificationCode.drop().catch(err => console.log('删除 VerificationCode 表时出错:', err.message))
        ]);

        // 重新启用外键约束
        await sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
        
        console.log('所有表删除完成');
      } catch (error) {
        console.error('删除表时出错:', error);
        throw error;
      }
    }

    // 按照依赖关系的顺序重建模型
    console.log('开始重建数据库表...');
    try {
      console.log('正在同步基础表...');
      await syncUser(false).then(() => console.log('User表同步成功'))
        .catch(err => console.error('User表同步失败:', err.stack));
      await SystemConfig.sync({ force: false }).then(() => console.log('SystemConfig表同步成功'))
        .catch(err => console.error('SystemConfig表同步失败:', err.stack));
      await Category.sync({ force: false }).then(() => console.log('Category表同步成功'))
        .catch(err => console.error('Category表同步失败:', err.stack));
      await Tag.sync({ force: false }).then(() => console.log('Tag表同步成功'))
        .catch(err => console.error('Tag表同步失败:', err.stack));
      
      console.log('正在同步中间依赖表...');
      await syncRechargeRecord(false).then(() => console.log('RechargeRecord表同步成功'))
        .catch(err => console.error('RechargeRecord表同步失败:', err.stack));
      await syncMaterial(false).then(() => console.log('Material表同步成功'))
        .catch(err => console.error('Material表同步失败:', err.stack));
      await MaterialTag.sync({ force: false }).then(() => console.log('MaterialTag表同步成功'))
        .catch(err => console.error('MaterialTag表同步失败:', err.stack));
      await VerificationCode.sync({ force: false }).then(() => console.log('VerificationCode表同步成功'))
        .catch(err => console.error('VerificationCode表同步失败:', err.stack));
      
      console.log('正在同步依赖表...');
      await syncMaterialOrder(false).then(() => console.log('MaterialOrder表同步成功'))
        .catch(err => console.error('MaterialOrder表同步失败:', err.stack));
      await syncPayment(false).then(() => console.log('Payment表同步成功'))
        .catch(err => console.error('Payment表同步失败:', err.stack));
      await Cart.sync({ force: false }).then(() => console.log('Cart表同步成功'))
        .catch(err => console.error('Cart表同步失败:', err.stack));
      await Download.sync({ force: false }).then(() => console.log('Download表同步成功'))
        .catch(err => console.error('Download表同步失败:', err.stack));
      await ConsumptionRecord.sync({ force: false }).then(() => console.log('ConsumptionRecord表同步成功'))
        .catch(err => console.error('ConsumptionRecord表同步失败:', err.stack));
      await Transaction.sync({ force: false }).then(() => console.log('Transaction表同步成功'))
        .catch(err => console.error('Transaction表同步失败:', err.stack));
      
      console.log('所有表重建完成');
    } catch (error) {
      console.error('重建表时出错:', error);
      throw error;
    }

    // 初始化系统配置
    const [emailVerificationConfig] = await SystemConfig.findOrCreate({
      where: { key: 'emailVerificationEnabled' },
      defaults: {
        value: 'false',
        description: '是否开启用户注册邮箱验证'
      }
    });

    console.log('所有模型同步完成');

    return true;
  } catch (error) {
    console.error('模型初始化失败:', error);
    return false;
  }
};

module.exports = {
  sequelize,
  User,
  RechargeRecord,
  Payment,
  MaterialOrder,
  Material,
  SystemConfig,
  Cart,
  Category,
  Tag,
  Download,
  ConsumptionRecord,
  MaterialTag,
  Transaction,
  VerificationCode,
  initializeModels
};